package cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Administrator
 * @Date 2020/6/2 16:17
 **/
@WebServlet("/cookieTime")
public class CookieTime extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies=req.getCookies();
        resp.setContentType("text/html;charset=utf-8");
        boolean flag=false;
        if (cookies!=null&&cookies.length>0){
            for(Cookie c:cookies){
                String name=c.getName();
                if (name.equals("lastTime")){
                    String value =c.getValue();
                    value= URLDecoder.decode(value,"utf-8");

                    resp.getWriter().write("上次访问时间："+value);
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");



                    Date date=new Date();
                    String d=sdf.format(date);
                    String s= URLEncoder.encode(d,"utf-8");
                    c.setValue(s);
                    c.setMaxAge(3600*24);
                    resp.addCookie(c);
                    flag=true;
                    break;

                }
            }
        }

        if(cookies==null || cookies.length==0||!flag){
            resp.getWriter().write("欢迎首次访问");


            Date date=new Date();

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String d=sdf.format(date);
            String s= URLEncoder.encode(d,"utf-8");
            Cookie cookie=new Cookie("lastTime",s);
            resp.addCookie(cookie);
            cookie.setMaxAge(216000);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
